<template>
  <px-drawer v-model="visible" @open="openDrawer" @close="closeDrawer">
    <template #header>
      <h3 style="font-weight: bold">{{ typeTitle }}</h3>
    </template>
    <template #default>
      <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <px-form-item prop="supplyModel" label="厂商型号">
          <px-input
            v-model="formValue.supplyModel"
            placeholder="请输入厂商型号"
            maxlength="50"
            clearable
            @blur="formValue.supplyModel = $event.target.value.trim()"
          />
        </px-form-item>
        <px-form-item prop="model" label="厂内型号">
          <px-input v-model="formValue.model" placeholder="请输入厂内型号" maxlength="50" clearable @blur="formValue.model = $event.target.value.trim()" />
        </px-form-item>
        <px-form-item prop="category" label="种类">
          <px-select v-model="formValue.category" @change="handleCategoryChange" filterable clearable placeholder="请选择种类">
            <px-option v-for="item in categoryList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item prop="typeCode" label="类型"
          ><px-tree-select
            v-model="formValue.typeCode"
            placeholder="请选择类型名称"
            filterable
            clearable
            :data="typeList"
            :render-after-expand="false"
            :props="defaultProps"
            @visible-change="initTypeList"
            @change="handleTypeChange"
          />
        </px-form-item>
        <px-form-item prop="brandCode" label="品牌">
          <px-select :disabled="!formValue.typeCode" v-model="formValue.brandCode" filterable clearable placeholder="请选择品牌">
            <px-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.code" />
          </px-select>
        </px-form-item>
        <px-form-item label="排序" prop="sort">
          <px-input-number v-model="formValue.sort" :min="0" controls-position="right" />
        </px-form-item>
      </px-form>
    </template>
    <template #footer>
      <px-button @click="closeDrawer">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </template>
  </px-drawer>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { queryListTree_1, saveSparePartModel, updateSparePartModel, queryBrandList } from "@/api/equip/spareParts";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs } from "vue";

// 调用父级-关闭抽屉、查询列表方法
const emits = defineEmits(["closeDrawer", "queryTable"]);
// 父级传过来的值
const props = defineProps(["visible", "drawerType", "typeTitle", "sparePartsRow"]);
const visible = computed(() => props.visible);
// 页面本身的值
// 树形选择图
const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
const formRef = ref();
const initFormValue = {
  id: "",
  className: "",
  category: "",
  parentName: "",
  typeName: "",
  sort: 0
};
const state = reactive<any>({
  formValue: initFormValue,
  categoryList: [],
  typeList: [],
  brandList: []
});
const { formValue, categoryList, typeList, brandList } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  supplyModel: [{ required: true, message: "厂商型号不能为空", trigger: ["blur", "change"] }],
  model: [{ required: true, message: "厂内型号不能为空", trigger: ["blur", "change"] }],
  typeCode: [{ required: true, message: "类型不能为空", trigger: ["blur", "change"] }],
  category: [{ required: true, message: "种类不能为空", trigger: ["blur", "change"] }],
  brandCode: [{ required: true, message: "品牌不能为空", trigger: ["blur", "change"] }]
}));
// 打开抽屉
const openDrawer = () => {
  formRef.value.resetFields();
  if (props.drawerType === "add") {
    formValue.value = { ...initFormValue, ...props.sparePartsRow };
  } else if (props.drawerType === "edit") {
    formValue.value = { ...props.sparePartsRow };
  }
  initCategory();
  initBrandList();
  initTypeList(true);
};
// 种类改变，清空类型
const handleCategoryChange = () => {
  typeList.value = [];
  brandList.value = [];
  formValue.value.typeCode = undefined;
  formValue.value.brandCode = undefined;
};
// 种类下拉框
const initCategory = async () => {
  categoryList.value = [];
  const params = {
    typeCode: "typeCategory"
  };
  const data = await queryDictData(params);
  categoryList.value = data;
};
const setCategory = (list, params, val) => {
  list.forEach(item => {
    if (item.code === val) {
      params.value.category = item.category;
    } else if (item.children?.length) {
      setCategory(item.children, params, val);
    }
  });
};
// 类型改变，改变种类
const handleTypeChange = val => {
  if (!formValue.value.category) {
    setCategory(typeList.value, formValue, val);
  }
  formValue.value.brandCode = undefined;
  initBrandList();
};
// 类型下拉框
const initTypeList = async flag => {
  if (flag) {
    const data = await queryListTree_1({ category: formValue.value.category });
    typeList.value = data;
  } else {
    typeList.value = [];
  }
};
// 品牌下拉框
const initBrandList = async () => {
  if (formValue.value.typeCode) {
    const data: any = await queryBrandList({ pageSize: 9999 });
    brandList.value = data || [];
  }
};
// 提交按钮
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = formValue.value;
      if (props.drawerType === "add") {
        await saveSparePartModel(params);
        PxMessage.success("新增成功");
        emits("closeDrawer");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        await updateSparePartModel(params);
        PxMessage.success("编辑成功");
        emits("closeDrawer");
        emits("queryTable");
      }
    }
  });
};
// 关闭抽屉
const closeDrawer = () => {
  formRef.value.resetFields();
  emits("closeDrawer");
};
</script>
<style lang="scss" scoped>
:deep(.px-select) {
  width: 100%;
}
</style>
